//! # 观测性统一管理器实现
//! 
//! 提供观测性管理器的具体实现，集成指标、追踪、日志等功能。
//! 负责协调各个观测性组件的工作。

use super::traits::{ObservabilityManager, TracingProcessor, LogManager, ObservabilityMetricsCollector, LogLevel};
use super::context::{ObservabilityContext, ContextManager};
use super::config::ObservabilityConfig;
use rustcloud_core::{ServiceResult, ServiceError};
use rustcloud_metrics::{MetricsCollector, MetricType, Labels};
use std::sync::Arc;
use std::collections::HashMap;
use tokio::sync::RwLock;
use async_trait::async_trait;
use std::hash::{Hash, Hasher};

/// 统一观测性管理器实现
/// 
/// 作为观测性系统的中央协调器，管理所有观测性组件的生命周期和交互。
pub struct UnifiedObservabilityManager {
    /// 配置
    config: ObservabilityConfig,
    
    /// 指标收集器
    metrics_collector: Option<Arc<dyn MetricsCollector>>,
    
    /// 追踪处理器
    tracing_processor: Option<Arc<dyn TracingProcessor>>,
    
    /// 日志管理器
    log_manager: Option<Arc<dyn LogManager>>,
    
    /// 观测性指标收集器
    observability_metrics: Option<Arc<dyn ObservabilityMetricsCollector>>,
    
    /// 上下文管理器
    context_manager: ContextManager,
    
    /// 活跃上下文存储
    active_contexts: Arc<RwLock<HashMap<String, ObservabilityContext>>>,
}

impl UnifiedObservabilityManager {
    /// 创建新的统一观测性管理器
    /// 
    /// # 参数
    /// * `config` - 观测性配置
    /// 
    /// # 返回值
    /// 新的管理器实例
    pub fn new(config: ObservabilityConfig) -> Self {
        Self {
            config,
            metrics_collector: None,
            tracing_processor: None,
            log_manager: None,
            observability_metrics: None,
            context_manager: ContextManager::new(),
            active_contexts: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// 设置指标收集器
    /// 
    /// # 参数
    /// * `collector` - 指标收集器实现
    pub fn with_metrics_collector(mut self, collector: Arc<dyn MetricsCollector>) -> Self {
        self.metrics_collector = Some(collector);
        self
    }

    /// 设置追踪处理器
    /// 
    /// # 参数
    /// * `processor` - 追踪处理器实现
    pub fn with_tracing_processor(mut self, processor: Arc<dyn TracingProcessor>) -> Self {
        self.tracing_processor = Some(processor);
        self
    }

    /// 设置日志管理器
    /// 
    /// # 参数
    /// * `manager` - 日志管理器实现
    pub fn with_log_manager(mut self, manager: Arc<dyn LogManager>) -> Self {
        self.log_manager = Some(manager);
        self
    }

    /// 设置观测性指标收集器
    /// 
    /// # 参数
    /// * `collector` - 观测性指标收集器实现
    pub fn with_observability_metrics(mut self, collector: Arc<dyn ObservabilityMetricsCollector>) -> Self {
        self.observability_metrics = Some(collector);
        self
    }

    /// 启动观测性管理器
    /// 
    /// 启动各种后台任务，如上下文清理、数据导出等。
    pub async fn start(&self) -> ServiceResult<()> {
        // 启动上下文清理任务
        self.start_context_cleanup_task().await;
        
        // 启动数据导出任务
        self.start_export_tasks().await;
        
        tracing::info!("观测性管理器启动完成");
        Ok(())
    }

    /// 停止观测性管理器
    /// 
    /// 优雅停止所有后台任务并导出剩余数据。
    pub async fn stop(&self) -> ServiceResult<()> {
        // 导出所有剩余数据
        self.export_all().await?;
        
        tracing::info!("观测性管理器停止完成");
        Ok(())
    }

    /// 添加追踪事件
    /// 
    /// # 参数
    /// * `context_id` - 上下文ID
    /// * `name` - 事件名称
    /// * `attributes` - 事件属性
    pub async fn add_trace_event(&self, context_id: &str, name: &str, attributes: HashMap<String, serde_json::Value>) -> ServiceResult<()> {
        if !self.config.tracing_enabled || context_id.is_empty() {
            return Ok(());
        }

        let context = {
            let contexts = self.active_contexts.read().await;
            contexts.get(context_id).cloned()
        };

        if let Some(context) = context {
            if let Some(ref processor) = self.tracing_processor {
                processor.add_event(&context, name, attributes).await?;
            }
        }

        Ok(())
    }

    /// 记录结构化日志
    /// 
    /// # 参数
    /// * `level` - 日志级别
    /// * `message` - 日志消息
    /// * `fields` - 结构化字段
    /// * `context` - 观测性上下文（可选）
    pub async fn log_structured(&self, level: LogLevel, message: &str, fields: HashMap<String, serde_json::Value>, context: Option<&ObservabilityContext>) -> ServiceResult<()> {
        if !self.config.logging_enabled || !self.should_sample_log() {
            return Ok(());
        }

        if let Some(ref manager) = self.log_manager {
            manager.log_structured(level, message, fields, context).await?;
        }

        Ok(())
    }

    /// 导出所有观测性数据
    pub async fn export_all(&self) -> ServiceResult<()> {
        // 导出指标
        if self.config.metrics_enabled {
            if let Some(ref collector) = self.metrics_collector {
                // 指标收集器通常由外部系统pull，这里可以触发推送
                tracing::debug!("导出指标数据");
            }
        }

        // 导出追踪数据
        if self.config.tracing_enabled {
            if let Some(ref processor) = self.tracing_processor {
                processor.export().await?;
            }
        }

        // 导出日志数据
        if self.config.logging_enabled {
            if let Some(ref manager) = self.log_manager {
                manager.export().await?;
            }
        }

        Ok(())
    }

    /// 获取活动上下文统计
    pub async fn get_active_contexts_count(&self) -> usize {
        self.active_contexts.read().await.len()
    }

    /// 清理过期上下文
    /// 
    /// # 参数
    /// * `max_age` - 最大存活时间
    /// 
    /// # 返回值
    /// 被清理的上下文数量
    pub async fn cleanup_expired_contexts(&self, max_age: std::time::Duration) -> ServiceResult<usize> {
        let mut contexts = self.active_contexts.write().await;
        let before_count = contexts.len();
        
        let now = std::time::Instant::now();
        contexts.retain(|_, context| {
            now.duration_since(context.start_time) < max_age
        });
        
        let cleaned_count = before_count - contexts.len();
        if cleaned_count > 0 {
            tracing::info!("清理了 {} 个过期的观测性上下文", cleaned_count);
        }
        
        Ok(cleaned_count)
    }

    /// 启动上下文清理任务
    async fn start_context_cleanup_task(&self) {
        let contexts = self.active_contexts.clone();
        let cleanup_interval = self.config.context_cleanup_interval();
        let max_age = self.config.context_max_age();

        tokio::spawn(async move {
            let mut interval = tokio::time::interval(cleanup_interval);
            
            loop {
                interval.tick().await;
                
                let mut contexts_guard = contexts.write().await;
                let before_count = contexts_guard.len();
                
                let now = std::time::Instant::now();
                contexts_guard.retain(|_, context| {
                    now.duration_since(context.start_time) < max_age
                });
                
                let cleaned_count = before_count - contexts_guard.len();
                if cleaned_count > 0 {
                    tracing::debug!("自动清理了 {} 个过期的观测性上下文", cleaned_count);
                }
                
                drop(contexts_guard);
            }
        });
    }

    /// 启动数据导出任务
    async fn start_export_tasks(&self) {
        let export_interval = self.config.export_interval();
        
        // 克隆需要的组件引用
        let tracing_processor = self.tracing_processor.clone();
        let log_manager = self.log_manager.clone();
        let tracing_enabled = self.config.tracing_enabled;
        let logging_enabled = self.config.logging_enabled;

        tokio::spawn(async move {
            let mut interval = tokio::time::interval(export_interval);
            
            loop {
                interval.tick().await;
                
                // 导出追踪数据
                if tracing_enabled {
                    if let Some(ref processor) = tracing_processor {
                        if let Err(e) = processor.export().await {
                            tracing::error!("导出追踪数据失败: {}", e);
                        }
                    }
                }

                // 导出日志数据
                if logging_enabled {
                    if let Some(ref manager) = log_manager {
                        if let Err(e) = manager.export().await {
                            tracing::error!("导出日志数据失败: {}", e);
                        }
                    }
                }
            }
        });
    }

    /// 采样决策 - 追踪
    fn should_sample_trace(&self) -> bool {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        std::time::SystemTime::now().hash(&mut hasher);
        let hash = hasher.finish();
        let threshold = (self.config.sampling.trace_sampling_rate * u64::MAX as f64) as u64;
        hash <= threshold
    }

    /// 采样决策 - 指标
    fn should_sample_metrics(&self) -> bool {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        std::time::SystemTime::now().hash(&mut hasher);
        let hash = hasher.finish();
        let threshold = (self.config.sampling.metrics_sampling_rate * u64::MAX as f64) as u64;
        hash <= threshold
    }

    /// 采样决策 - 日志
    fn should_sample_log(&self) -> bool {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        std::time::SystemTime::now().hash(&mut hasher);
        let hash = hasher.finish();
        let threshold = (self.config.sampling.log_sampling_rate * u64::MAX as f64) as u64;
        hash <= threshold
    }
}

#[async_trait]
impl ObservabilityManager for UnifiedObservabilityManager {
    async fn start_context(&self, service_name: String, operation_name: String) -> ServiceResult<String> {
        if !self.should_sample_trace() {
            // 即使不采样，也要返回一个上下文ID以保持API一致性
            return Ok(format!("noop_{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
        }

        let mut context = ObservabilityContext::new(service_name, operation_name);
        
        // 添加默认标签
        for (key, value) in &self.config.default_labels {
            context.add_label(key.clone(), value.clone());
        }
        
        let context_id = context.trace_id.clone();
        
        if self.config.tracing_enabled {
            if let Some(ref processor) = self.tracing_processor {
                processor.start_span(&context).await?;
            }
        }
        
        // 存储上下文
        {
            let mut contexts = self.active_contexts.write().await;
            contexts.insert(context_id.clone(), context.clone());
        }
        
        // 同时存储到上下文管理器
        self.context_manager.store_context(context_id.clone(), context).await;
        
        Ok(context_id)
    }

    async fn end_context(&self, context_id: &str) -> ServiceResult<()> {
        // 如果是noop上下文，直接返回
        if context_id.starts_with("noop_") {
            return Ok(());
        }

        let context = {
            let mut contexts = self.active_contexts.write().await;
            contexts.remove(context_id)
        };
        
        if let Some(mut context) = context {
            context.complete();
            
            if self.config.tracing_enabled {
                if let Some(ref processor) = self.tracing_processor {
                    processor.end_span(&context).await?;
                }
            }
            
            // 记录性能指标
            if let Some(duration) = context.duration_ms() {
                if let Some(ref metrics) = self.observability_metrics {
                    metrics.record_performance_metric(&context.operation_name, duration as f64, Some(&context)).await?;
                }
            }
            
            // 从上下文管理器中移除
            self.context_manager.remove_context(context_id).await;
        }
        
        Ok(())
    }

    async fn record_error(&self, context_id: &str, error: &str) -> ServiceResult<()> {
        // 如果是noop上下文，直接返回
        if context_id.starts_with("noop_") {
            return Ok(());
        }

        let context = {
            let contexts = self.active_contexts.read().await;
            contexts.get(context_id).cloned()
        };
        
        if let Some(context) = context {
            // 记录错误日志
            self.log(LogLevel::Error, &format!("错误: {}", error), Some(&context)).await?;
            
            // 记录错误指标
            if let Some(ref metrics) = self.observability_metrics {
                metrics.record_error_metric("application_error", Some(&context)).await?;
            }
            
            // 更新上下文状态
            self.context_manager.update_context(context_id, |ctx| {
                ctx.mark_error(error.to_string());
            }).await;
        }
        
        Ok(())
    }

    async fn add_context_attribute(&self, context_id: &str, key: String, value: serde_json::Value) -> ServiceResult<()> {
        // 如果是noop上下文，直接返回
        if context_id.starts_with("noop_") {
            return Ok(());
        }

        // 更新活跃上下文
        {
            let mut contexts = self.active_contexts.write().await;
            if let Some(context) = contexts.get_mut(context_id) {
                context.add_attribute(key.clone(), value.clone());
            }
        }
        
        // 同时更新上下文管理器中的上下文
        self.context_manager.update_context(context_id, |ctx| {
            ctx.add_attribute(key, value);
        }).await;
        
        Ok(())
    }

    async fn record_counter(&self, name: &str, value: f64, labels: Labels) -> ServiceResult<()> {
        if !self.config.metrics_enabled || !self.should_sample_metrics() {
            return Ok(());
        }

        if let Some(ref collector) = self.metrics_collector {
            collector.record_counter(name, value, labels).await?;
        }
        
        Ok(())
    }

    async fn record_gauge(&self, name: &str, value: f64, labels: Labels) -> ServiceResult<()> {
        if !self.config.metrics_enabled || !self.should_sample_metrics() {
            return Ok(());
        }

        if let Some(ref collector) = self.metrics_collector {
            collector.record_gauge(name, value, labels).await?;
        }
        
        Ok(())
    }

    async fn record_histogram(&self, name: &str, value: f64, labels: Labels) -> ServiceResult<()> {
        if !self.config.metrics_enabled || !self.should_sample_metrics() {
            return Ok(());
        }

        if let Some(ref collector) = self.metrics_collector {
            collector.record_histogram(name, value, labels).await?;
        }
        
        Ok(())
    }

    async fn log(&self, level: LogLevel, message: &str, context: Option<&ObservabilityContext>) -> ServiceResult<()> {
        if !self.config.logging_enabled || !self.should_sample_log() {
            return Ok(());
        }

        if let Some(ref manager) = self.log_manager {
            manager.log(level, message, context).await?;
        }
        
        Ok(())
    }
}

/// 构建器模式用于创建观测性管理器
pub struct ObservabilityManagerBuilder {
    config: ObservabilityConfig,
    metrics_collector: Option<Arc<dyn MetricsCollector>>,
    tracing_processor: Option<Arc<dyn TracingProcessor>>,
    log_manager: Option<Arc<dyn LogManager>>,
    observability_metrics: Option<Arc<dyn ObservabilityMetricsCollector>>,
}

impl ObservabilityManagerBuilder {
    /// 创建新的构建器
    /// 
    /// # 参数
    /// * `config` - 观测性配置
    /// 
    /// # 返回值
    /// 新的构建器实例
    pub fn new(config: ObservabilityConfig) -> Self {
        Self {
            config,
            metrics_collector: None,
            tracing_processor: None,
            log_manager: None,
            observability_metrics: None,
        }
    }

    /// 设置指标收集器
    pub fn with_metrics_collector(mut self, collector: Arc<dyn MetricsCollector>) -> Self {
        self.metrics_collector = Some(collector);
        self
    }

    /// 设置追踪处理器
    pub fn with_tracing_processor(mut self, processor: Arc<dyn TracingProcessor>) -> Self {
        self.tracing_processor = Some(processor);
        self
    }

    /// 设置日志管理器
    pub fn with_log_manager(mut self, manager: Arc<dyn LogManager>) -> Self {
        self.log_manager = Some(manager);
        self
    }

    /// 设置观测性指标收集器
    pub fn with_observability_metrics(mut self, collector: Arc<dyn ObservabilityMetricsCollector>) -> Self {
        self.observability_metrics = Some(collector);
        self
    }

    /// 构建观测性管理器
    /// 
    /// # 返回值
    /// 配置好的观测性管理器实例
    pub fn build(self) -> UnifiedObservabilityManager {
        let mut manager = UnifiedObservabilityManager::new(self.config);
        
        if let Some(collector) = self.metrics_collector {
            manager = manager.with_metrics_collector(collector);
        }
        
        if let Some(processor) = self.tracing_processor {
            manager = manager.with_tracing_processor(processor);
        }
        
        if let Some(log_manager) = self.log_manager {
            manager = manager.with_log_manager(log_manager);
        }
        
        if let Some(observability_metrics) = self.observability_metrics {
            manager = manager.with_observability_metrics(observability_metrics);
        }
        
        manager
    }
}